<?php

namespace app\middleware;

use Closure;
use think\response\Json;

class Format
{
    /**
     * api接口数据返回结果内容的处理
     * 
     * @param $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        $response = $next($request);
        if($response instanceof Json){
            $data = $response->getData();
            if(!isset($data['code']) || !isset($data['msg'])){
                // 输出数据是否需要加密
                if(config('crypt.enable')){
                    $key = config('crypt.key');
                    $method = config('crypt.method');
                    $iv = config('crypt.iv');
                    $options = config('crypt.options');
                    //加密
                    $data = openssl_encrypt(serialize($data), $method, $key, $options, $iv);
                }
        
                $data = [
                    'code' => 200,
                    'msg' => 'Success',
                    'data' => $data
                ];
            }
            $response->data($data);
        }
        return $response;
    }
}
